package com.gange.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gange.constants.RedisPrefix;
import com.gange.entity.Admin;
import com.gange.exception.IllTokenException;
import com.gange.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gange
 * @since 2022-11-03
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    //获取RedisTemplate工具
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/tokens")
    public Map<String,String> login(@RequestBody Admin admin, HttpSession session){
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",admin.getUsername())
                .eq("password", DigestUtils.md5DigestAsHex(admin.getPassword().getBytes(StandardCharsets.UTF_8)));
        admin = adminService.getOne(wrapper);

        //1.判断admin是否查询出来。
        if(!ObjectUtils.isEmpty(admin)){
            //2.查询出来后往redis里面放数据。
            redisTemplate.opsForValue().set(RedisPrefix.TOKEN_KEY +session.getId(),admin,30, TimeUnit.MINUTES);
        }else{
            //3.没有查询出来，直接抛异常
            throw new IllTokenException("账号密码错误！！！");
        }

        Map<String,String> resultMap= new HashMap<>();
        resultMap.put("token",session.getId());
        return resultMap;
    }

    @GetMapping("/admin-user")
    public Map<String,String> userinfo(String token){
        Admin admin = (Admin)redisTemplate.opsForValue().get(RedisPrefix.TOKEN_KEY+token);
        Map<String,String> resultMap= new HashMap<>();
        resultMap.put("name",admin.getUsername());
        resultMap.put("avatar",admin.getAvatar());
        return resultMap;
    }

    @DeleteMapping("/tokens/{token}")
    public void logout(@PathVariable("token") String token){
        redisTemplate.delete(RedisPrefix.TOKEN_KEY+token);
    }
}

